<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/">权限管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDia">添加角色</el-button>
        </el-col>
        <el-col>
          <el-table :data="roleList" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row
                  :class="['bdbottom',i1 === 0 ? 'bdtop' : '','vcenter']"
                  v-for="(item1, i1) in scope.row.children"
                  :key="item1.id"
                >
                  <el-col :span="5">
                    <el-tag closable @close="closereomve(scope.row,item1.id)">{{ item1.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                    <el-row
                      :class="[i2 === 0?'':'bdtop','vcenter']"
                      v-for="(item2,i2) in item1.children"
                      :key="item2.id"
                    >
                      <el-col :span="6">
                        <el-tag
                          type="success"
                          closable
                          @close="closereomve(scope.row,item2.id)"
                        >{{ item2.authName}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <el-col :span="18">
                        <el-tag
                          type="warning"
                          closable
                          @close="closereomve(scope.row,item3.id)"
                          v-for="(item3, i3) in item2.children"
                          :key="item3.id"
                        >{{ item3.authName}}</el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column label="角色名称" prop="roleName"></el-table-column>
            <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="mini"
                  @click="editRole(scope.row)"
                >编辑</el-button>
                <el-button
                  type="warning"
                  icon="el-icon-search"
                  size="mini"
                  @click="delRole(scope.row)"
                >删除</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-search"
                  size="mini"
                  @click="showDialog(scope.row)"
                >分配权限</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog :title="titles" :visible.sync="dialogVisible" width="50%">
      <el-form
        :model="addroleFrom"
        ref="addroleFromRef"
        :rules="addroleFromRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addroleFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addroleFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addroleSaveInfo">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配权限" :visible.sync="setShowDialog" width="50%" @close="setCloseDia">
      <el-tree
        :data="treeList"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setShowDialog = false">取 消</el-button>
        <el-button type="primary" @click="setTreeSaveInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      roleList: [],
      setShowDialog: false,
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      roleid: '',
      dialogVisible: false,
      addroleFrom: {},
      titles: '添加角色',
      editId: '',
      addroleFromRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: "请输入描述", trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getrolesList()
  },
  methods: {
    addDia () {
      this.dialogVisible = true
      this.titles = '添加角色'
    },
    async editRole (role) {
      this.titles = '编辑角色'
      const { data: res } = await this.$http.get(`roles/${role.id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("获取编辑数据失败")
      }
      this.editId = role.id
      this.addroleFrom = res.data
      this.dialogVisible = true
    },
    async editRoleSave () {
      const { data: res } = await this.$http.put(`roles/${this.editId}`, {
        roleName: this.addroleFrom.roleName,
        roleDesc: this.addroleFrom.roleDesc
      })
      if (res.meta.status !== 200) {
        return this.$message.error('更新保存失败')
      }
      this.$message.success('更新成功')
      this.getrolesList()
      this.dialogVisible = false
      this.addroleFrom = {}
      return

    },
    async delRole (role) {
      const confirmResult = await this.$confirm("此操作将永久删除该权限, 是否继续?", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}`)
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败")
      }
      this.$message.success("删除成功")
      this.getrolesList()
    },
    async addroleSaveInfo () {
      if (this.titles === '编辑角色') {
        return this.editRoleSave()
      }
      this.$refs.addroleFromRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addroleFrom)
        if (res.meta.status !== 201) {
          return this.$message.error("添加角色失败")
        }
        this.$message.success("添加角色成功")
        this.dialogVisible = false
        this.getrolesList()
      })
    },
    async setTreeSaveInfo () {
      const keys = [
        ...this.$refs.treeRef.getHalfCheckedKeys(),
        ...this.$refs.treeRef.getCheckedKeys()
      ]

      const strId = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleid}/rights`, { rids: strId })
      if (res.meta.status !== 200) {
        return this.$message.error("更新失败")
      }
      this.$message.success("更新成功")
      this.getrolesList();
      this.setShowDialog = false
    },
    setCloseDia () {
      this.defKeys = []
    },
    async showDialog (role) {
      this.roleid = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error("获取树列表失败")
      }
      this.treeList = res.data
      console.log(res.data)
      this.getLeafkeys(role, this.defKeys)

      this.setShowDialog = true

    },
    // 通过递归 获取角色下三级权限的 id, 并保存到defKeys数组
    getLeafkeys (node, arr) {
      // 没有children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafkeys(item, arr))
    },
    // tag 删除事件
    async closereomve (role, rightId) {
      const confirmResult = await this.$confirm("此操作将永久删除该权限, 是否继续?", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败！')
      this.$message.success('删除用户成功！')
      role.children = res.data
    },
    async getrolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
      console.log(res.data)
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
.btns {
  display: flex;
  justify-content: center;
}
</style>